<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom">{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                    <a-col :md="6" :sm="24">
                        <a-form-item label="请选择时间">
                            <a-range-picker
                                    :placeholder="['开始时间', '结束时间']"
                                    v-model="rangeTime"
                                    format="YYYY-MM-DD"
                                    @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-if="showCompanys">
                        <a-form-item label="处置单位">
                            <select-company-list :isInitData="true" @change="changeCompany" ></select-company-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-has="AUTH.SHOW_RECYCLE_USER">
                        <a-form-item label="回收员姓名:">
                            <select-collector-list ref="refSelectCollectorList" @change="changeCollectorName"></select-collector-list>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>

            <div style="float: right">
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download"
                          @click="handleMwExportXlsForImages">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType :companysId="queryParam.companysId" @change="changeWasteType"></CheckboxWasteType>
        </div>
        <div>
            <div class="ant-alert ant-alert-success" style="margin-bottom: 16px;">
                <span class="countySum">统计：
                    <span v-for="(item,index) in sumData" :key="index">
                        【{{item.wasteName}}：{{item.sumWasteOriginalValue}}{{item.priceUnit || ''}}
                        <span v-if="item.sumWasteOriginalNumber && item.sumWasteOriginalNumber>0"> / {{item.sumWasteOriginalNumber}}袋</span>】
                    </span>
                </span>
            </div>

            <div>
                <a-table
                        ref="table"
                        size="middle"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="ipagination"
                        :loading="loading"
                        class="j-table-force-nowrap"
                        @change="handleTableChange"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div v-html="text"></div>
                    </template>
                    <template slot="imgSlot" slot-scope="text">
                        <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                        <img v-else :src="text" height="25px" alt style="width: auto;height: 50px;"/>
                    </template>
                </a-table>
            </div>
        </div>


        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">{{title}}</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                </a-table>
            </div>
        </div>


    </a-card>
</template>

<script>
    /**
     * create by Yang
     * 按回收员统计回收数据
     */

    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectCollectorList from '@/components/Jane/SelectCollectorList'
    import SelectCompanyList from '@/components/Jane/SelectCompanyList'
    import { downloadFile } from '@/api/manage' // 模糊下拉查询
    import { getAction } from '@/api/manage'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

    import { GET_USER_AUTH } from '@/utils/util'

    export default {
        name: 'GeneralSolidWaste',
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            SelectCollectorList,
            SelectCompanyList,
            CheckboxWasteType
        },
        data() {
            return {
                title: '按回收员统计回收数据',
                rangeTime : [],
                queryParam:{
                    creatTimeBegin : null,
                    creatTimeEnd : null,
                },
                // 表头
                columns: [],
                url: {
                    list: null,
                    exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportRecordPersonData'
                },
                AUTH:{
                    SHOW_RECYCLE_USER : 'show:recycle:user'
                },
                // 数据统计
                sumData:[]
            }
        },
        watch:{
            requestResult(newValue,oldValue){
                if(newValue && newValue.wasteSum){
                    this.sumData = newValue.wasteSum || [];
                }
            }
        },
        computed:{
            // 是否显示处置单位的筛选条件
            showCompanys(){
                let state = true;
                let userInfo = this.$store.getters.userInfo
                if(userInfo.companysId){
                    state = false;
                }
                return state;
            },
        },
        methods: {
            // 初始化配置信息
            async initDictConfig() {
                // 获取到用户登陆的信息
                let userInfo = this.$store.getters.userInfo
                // 如果用户有处置单位
                if (userInfo.companysId) {
                    // 则用户的处置单位id为参数companysId
                    this.queryParam.companysId = userInfo.companysId;
                    // 判断当前用户是否有筛选回收员的权限，只设置了处置单位有该权限
                    if(GET_USER_AUTH(this.AUTH.SHOW_RECYCLE_USER)){
                        // 有，则查询回收员列表信息，渲染组件
                        await this.refreshRecycleUser();
                    }else{
                        // 没有，这说明当前用户是回收员，则直接根据它的id去查询
                        this.queryParam.recyclePersonId = userInfo.id;
                    }
                }
                this.queryParam.creatTimeBegin = new Date().MonthFirstDay()
                this.queryParam.creatTimeEnd = new Date().MonthLastDay()
                this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd]

            },

            // 查询回收员信息
            async refreshRecycleUser(){
                let _this = this;
                setTimeout(async() => {
                    let ref = await _this.$refs.refSelectCollectorList;
                    if(ref && ref.initData && _this.queryParam.companysId){
                        await ref.initData(_this.queryParam.companysId);
                    }
                },500)
            },

            // 废物类型选择改变
            async changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.url.list = '/hc/hcRecycleRecord/queryRecordPersonData';
                await this.loadData()
                this.setColumns()
            },


            // 选择处置单位
            async changeCompany(value) {
                this.queryParam.companysId = value;
                this.queryParam.recyclePersonId = '';
                await this.refreshRecycleUser();
                this.searchQuery()
            },

            // 选择时间
            handleDateChange(value, dateString) {
                this.rangeTime = dateString
                if (dateString[0]) {
                    this.queryParam.creatTimeBegin = dateString[0]
                }
                if (dateString[1]) {
                    this.queryParam.creatTimeEnd = dateString[1]
                }
            },

            // 选择回收员
            changeCollectorName(value,option){
                this.queryParam.recyclePersonId = value;
            },
            // 查询数据
            searchQuery: function() {
                this.queryParam.wasteId = this.wasteId.join(',')
                this.loadData(1)
            },

            // 导出
            handleMwExportXlsForImages() {
                let param = { ...this.queryParam }
                let name = `回收数据统计-${new Date().FormatDate()}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages, name, param)
            },
            // 设置表格头部信息
            setColumns() {
                let data = this.wasteTypeList
                let cols = []
                data.forEach((item, index) => {
                    if (item.wasteTypeName) {
                        let child = [];
                        (item['children'] || []).forEach((val, i) => {
                            let info = this.wasteId.find(v => v === val.id)
                            if (info) {
                                // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                              if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                val.priceUnit = "kg"
                              }
                                child.push({
                                    title: val.wasteTypeName,
                                    dataIndex: 'id',
                                    key: `${index}-${i}`,
                                    children: [
                                        {
                                            title: '袋/箱数',
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-0`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                if(info){
                                                    return `${info.wasteOriginalNumber || 0}`
                                                }
                                                return ''
                                            }
                                        },
                                        {
                                            title: `重量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                if(info){
                                                    return `${info.wasteOriginalValue || 0}`
                                                }
                                                return ''
                                            }
                                        }
                                    ]
                                })
                            }
                        })
                        if (child.length) {
                            let obj = {
                                title: item.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}`,
                                children: child
                            }
                            cols.push(obj)
                        }
                    }
                })
                this.columns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        customRender: function(t, r, index) {
                            return parseInt(index) + 1
                        }
                    },
                    {
                        title: '回收员',
                        align: 'center',
                        dataIndex: 'recycleOriginalPersonName',

                    },
                    ...cols,
                ]
            },

        }
    }
</script>

<style scoped>
.countySum{
    font-weight: 600;
    color:#F5F5F5;
}
</style>
